package initialize

import (
	"fmt"

	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"gopkg.in/yaml.v3"

	"shop_srvs/user_srv/global"
)

func GetEnvInfo(env string) bool {
	viper.AutomaticEnv()
	return viper.GetBool(env)
}

func InitConfig() {
	debug := GetEnvInfo("env")
	configFilePrefix := "config"
	configFileName := fmt.Sprintf("%s-pro", configFilePrefix)
	if debug {
		configFileName = fmt.Sprintf("debug-%s", configFilePrefix)
	}

	v := viper.New()
	v.SetConfigType("yaml")
	v.SetConfigName(configFileName)
	v.AddConfigPath("/Users/tao/Documents/WorkSpace/shop_srvs/user_srv/")

	if err := v.ReadInConfig(); err != nil {
		panic(err)
	}
	if err := v.Unmarshal(global.NacosConfig); err != nil {
		panic(err)
	}
	zap.S().Infof("配置信息: %v", global.NacosConfig)

	nacosConfig := global.NacosConfig.Nacos
	// 从 nacos 中获取配置信息
	sc := []constant.ServerConfig{
		{
			IpAddr: nacosConfig.Host,
			Port:   nacosConfig.Port,
		},
	}

	cc := constant.ClientConfig{
		NamespaceId:         nacosConfig.Namespace,
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "log/nacos/log",
		CacheDir:            "log/nacos/cache",
		LogLevel:            "debug",
	}

	configClient, err := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": sc,
		"clientConfig":  cc,
	})
	if err != nil {
		panic(err)
	}

	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: nacosConfig.DataId,
		Group:  nacosConfig.Group,
	})

	if err != nil {
		panic(err)
	}

	if err := yaml.Unmarshal([]byte(content), &global.ServerConfig); err != nil {
		panic(err)
	}

	zap.S().Infof("从nacos读取配置信息: %v", global.ServerConfig)

	// 监控配置变化
	if err := configClient.ListenConfig(vo.ConfigParam{
		DataId: nacosConfig.DataId,
		Group:  nacosConfig.Group,
		OnChange: func(namespace, group, dataId, data string) {
			if err := yaml.Unmarshal([]byte(data), &global.ServerConfig); err != nil {
				panic(err)
			}
			zap.S().Info("nacos配置变化了, %v", global.ServerConfig)
		},
	}); err != nil {
		panic(err)
	}
}
